<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->title = 'Блог';
        $this->view->headTitle()->setSeparator(' | ');
        $this->view->headTitle($this->view->title);
        $categories = new Application_Model_DbTable_Categories();
        $this->view->categories = $categories->fetchAll();
    }

    public function indexAction()
    {
        $posts = new Application_Model_DbTable_Posts();
        $this->view->posts = $posts->getAllPosts();
    }

    /**
     * View post
     * 
     * @return void
     */
    public function postAction()
    {
        $id = intval($this->_getParam('id', 0));
        if ($id > 0) {
            $post = new Application_Model_DbTable_Posts();
            $this->view->post = $post->getById($id);
            $this->view->postTitle = $this->view->post['title'];
            $this->view->headTitle($this->view->postTitle);

            $comments = new Application_Model_DbTable_Comments();
            $this->view->comments = $comments->getByPostId($id);

            // Форма комментариев
            $form = new Application_Form_Comment();
            $form->postId->setValue($id);
            $this->view->form = $form;

            if ($this->getRequest()->isPost()) {
                $formData = $this->getRequest()->getPost();
                if ($form->isValid($formData)) {
                    $postId  = intval($form->getValue('postId'));
                    $name    = $form->getValue('name');
                    $email   = $form->getValue('email');
                    $url     = $form->getValue('url');
                    $comment = $form->getValue('blogComment');
                    $comments->add($postId, $name, $email, $url, $comment);
                    $this->message = "Комментарий оставлен";
                } else {
                    $this->message = "Комментарий не оставлен! Валидация не пройдена!";
                    $form->populate($formData);
                }
            }
        }
    }

    /**
     * View category
     * 
     * @return void
     */
    public function categoryAction()
    {
        $id = intval($this->_getParam('id', 0));
        if ($id > 0) {
            $posts = new Application_Model_DbTable_Posts();
            $this->view->posts = $posts->getByCategoryId($id);
            // Получаем данные по категории
            $category = new Application_Model_DbTable_Categories();
            $this->view->category = $category->getById($id);
            // Устанавливаем заголовок для категории в тег title
            $this->view->categoryTitle = $this->view->category['title'];
            $this->view->headTitle($this->view->categoryTitle);
        }
    }

}